package com.keiou.drink.api;

import android.net.ParseException;

import com.google.gson.JsonParseException;
import com.keiou.drink.api.exception.ApiException;
import com.keiou.drink.util.TLog;

import org.json.JSONException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 作者 ：Bob on 2017/6/5.
 * 邮箱 ：motherlovefather@126.com
 */

public abstract class AbsSubscriber<T> extends Subscriber<T> {

    //对应HTTP的状态码
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    /*自定义状态码*/
    public static final int UNKNOWN = 1000;
    public static final int PARSE_ERROR = 1001;
    public static final int INVALID_ACCESSTOKEN = 4012;


    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        TLog.e("onError");
        Throwable throwable = e;
        //获取最根源的异常
        while (throwable.getCause() != null) {
            e = throwable;
            throwable = throwable.getCause();
        }

        ApiException ex = null;
        if (e instanceof HttpException) {             //HTTP错误
            HttpException httpException = (HttpException) e;

            ex = new ApiException(UNKNOWN, "网络连接失败,请稍后重试");
            onError(ex);

//            switch (httpException.code()) {
//                case UNAUTHORIZED:
//                case FORBIDDEN:
//                case NOT_FOUND:
//                case REQUEST_TIMEOUT:
//                case GATEWAY_TIMEOUT:
//                case INTERNAL_SERVER_ERROR:
//                case BAD_GATEWAY:
//                case SERVICE_UNAVAILABLE:
//                default:
//                    ex = new ApiException(UNKNOWN, "网络连接失败,请稍后重试");
//                    onError(ex);
//                    break;
//            }
        } else if (e instanceof ApiException) {    //服务器返回的错误
            ex = (ApiException) e;
            onError(ex);
            //  intercept(resultException.getCode());
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            ex = new ApiException(PARSE_ERROR, "数据解析失败");
            onError(ex);
        } else {
            ex = new ApiException(UNKNOWN, "网络连接失败,请稍后重试");
            onError(ex);
        }

        if (null != ex)
            onIntercept(ex.getCode());

    }


    /**
     * 错误回调
     */
    protected abstract void onError(ApiException ex);

    protected abstract void onIntercept(int code);

}
